package cn.pzhuweb.controller;

import cn.pzhuweb.pojo.User;
import cn.pzhuweb.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;

/**
 * Servlet implementation class TodoServlet
 */

public class JDBCServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private PreparedStatement sta;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public JDBCServlet() {
        super();
        // TODO Auto-generated constructor stub
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");
        Connection con = null;
        PreparedStatement sta = null;
        HashMap<String, User> map = null;
        ResultSet res = null;
        try {
            con = DBUtil.getConnection();
            // 3.编写SQL
            String username = request.getParameter("username");
            // String sql = "select * from user where name='"+username+"'";
            if (username != "" && username != null) {
                //效果为：SELECT * FROM USER WHERE NAME LIKE  "%"'1'"%";
                String sql = "select * from user where name like  \"%\"?\"%\"";
                // 4.创建命令对象
                // Statement sta = con.createStatement();
                sta = con.prepareStatement(sql);
                // 5.执行命令
                // ResultSet res = sta.executeQuery(sql);
                sta.setString(1, username);
            } else {
                String sql = "select * from user";
                sta = con.prepareStatement(sql);
            }
            res = sta.executeQuery();
            // 6.处理结果
            map = new HashMap<>();// 保存结果集中的所有用户信息
            while (res.next()) {
                String name = res.getString(1);
                String psw = res.getString(2);
                User temp = new User(name, psw);
                map.put(name, temp);// 将这一行的user加入集合中
            }
            request.getSession().setAttribute("map", map);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 7. 释放资源
            DBUtil.close(res, sta, con);
        }
        response.sendRedirect("show.jsp");
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}
